/* 
 * File:   GraphicObject.cpp
 * Author: ferranferri
 * 
 * Created on June 13, 2013, 5:17 PM
 */

#include "GraphicObject.h"
#include "core/core_utils.h"
#include "z3d/graphics/geometry/Z3D_Mesh.h"
#include "z3d/graphics/shader/Program.h"

namespace z3d{
    GraphicObject::GraphicObject()
        :_mesh(NULL)
        ,_program(NULL)
    {
    }

    void GraphicObject::setMesh(Z3D_Mesh* mesh) {
        assertion(_mesh == NULL, "Mesh is already initialized");
        assertion(mesh != NULL, "Mesh is Null");
        _mesh = mesh;
    }
    
    void GraphicObject::setProgram(Program* program) {
        assertion(_program == NULL, "Program is already initialized");
        assertion(program != NULL, "Program is Null");
        _program = program;
    }
    
    void GraphicObject::bindProgramToMesh() {
        // connect the xyz to the "vert" attribute of the vertex shader
        glEnableVertexAttribArray(_program->attrib("vert"));
        glVertexAttribPointer(_program->attrib("vert"), 3, GL_FLOAT, GL_FALSE, 0, NULL);
    }
    
    void GraphicObject::display() {
        // bind the program (the shaders)
        glUseProgram(_program->object());

        // bind the VAO (the triangle)
        glBindVertexArray(_mesh->getVertexArrayObjectId());

        // draw the VAO
        glDrawArrays(GL_TRIANGLES, 0, 3);

        // unbind the VAO
        glBindVertexArray(0);

        // unbind the program
    glUseProgram(0);
    }
    
    GraphicObject::~GraphicObject() {
        if(_mesh != NULL)
            delete _mesh;
        if(_program != NULL)
            delete _program;
        
    }
}